package com.zhihu.matisse.library.engine.impl;

import com.zhihu.matisse.library.engine.ImageEngine;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.FileNotFoundException;

public class SimpleImageEngine implements ImageEngine {
    @Override
    public void loadThumbnail(Context context, int resize, PixelMap placeholder, Image imageView, Uri uri) {
        imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
        if (placeholder != null){
            imageView.setBackground(new PixelMapElement(placeholder));
        }
        loadImage(context,resize,resize,imageView,uri);
    }

    @Override
    public void loadGifThumbnail(Context context, int resize, PixelMap placeholder, Image imageView, Uri uri) {
        imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
        if (placeholder != null){
            imageView.setBackground(new PixelMapElement(placeholder));
        }
        loadImage(context,resize,resize,imageView,uri);
    }

    @Override
    public void loadImage(Context context, int resizeX, int resizeY, Image imageView, Uri uri) {
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        try {
            ImageSource imageSource = ImageSource.create(DataAbilityHelper.creator(context).openFile(uri, "r"),options);
            if (imageSource != null){
                setImage(imageSource,resizeX,resizeY,imageView);
            }
        } catch (FileNotFoundException | DataAbilityRemoteException e) {
            e.printStackTrace();
        }
    }
    private void setImage(ImageSource imageSource,int resizeX, int resizeY, Image imageView){
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.editable = true;
        decodingOptions.sampleSize = 1;
        if (resizeX == 0 && resizeY == 0){
            //TODO 0
        }else {
            decodingOptions.desiredSize = new Size(resizeX,resizeY);
        }
        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);

        imageView.setPixelMap(pixelMap);
    }

    @Override
    public void loadGifImage(Context context, int resizeX, int resizeY, Image imageView, Uri uri) {
        loadImage(context,resizeX,resizeY,imageView,uri);
    }

    @Override
    public boolean supportAnimatedGif() {
        return false;
    }
}
